<template>
  <div class="addAndEditProjectContent">
    <!-- v-bind="{ layout: 'vertical' }" -->
    <a-form
      ref="formRef"
      v-bind="{ layout: 'vertical' }"
      :model="formModel"
      :rules="rules"
      :disabled="disabled || specialDisabled"
    >
      <a-form-item
        has-feedback
        :label="t('addAndEditProject', '项目名称')"
        name="name"
      >
        <a-input
          v-model:value="formModel.name"
          autocomplete="off"
          :placeholder="t('common', '请输入')"
        />
      </a-form-item>
      <div class="subTitle">{{ t('addAndEditProject', '项目设置') }}</div>
      <div
        style="display: flex; justify-content: space-between; flex-wrap: wrap"
      >
        <a-form-item
          has-feedback
          :label="t('addAndEditProject', '年级')"
          name="grade"
          style="width: 200px"
        >
          <minDatePicker
            v-model:value="formModel.grade"
            picker="year"
            :disabledDate="disabledDate"
            :placeholder="t('common', '请选择')"
            style="margin-right: 12px; width: 100%"
          />
        </a-form-item>
        <a-form-item
          has-feedback
          :label="t('addAndEditProject', '班级')"
          name="gradeClass"
          style="width: 200px"
          v-if="formModel.grade"
        >
          <a-select
            v-model:value="formModel.gradeClass"
            mode="multiple"
            style="width: 100%; margin-right: 12px"
            :placeholder="t('common', '不限班级')"
          >
            <a-select-option
              :value="item.id"
              v-for="item in newSelectStructure.gradeClass"
              >{{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item
          has-feedback
          :label="t('addAndEditProject', '项目类型')"
          name="category"
          style="width: 200px"
        >
          <a-select
            allowClear
            v-model:value="formModel.category"
            style="width: 100%; margin-right: 12px"
            :placeholder="t('common', '请选择')"
          >
            <a-select-option
              :value="item.dictValue"
              v-for="item in newSelectStructure.category"
              >{{ item.dictName }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item
          has-feedback
          :label="t('addAndEditProject', '项目模板')"
          name="template"
          style="width: 200px"
        >
          <a-select
            allowClear
            v-model:value="formModel.template"
            style="width: 100%; margin-right: 12px"
            :placeholder="t('common', '请选择')"
          >
            <a-select-option
              :value="item.value"
              v-for="item in newSelectStructure['template']"
              >{{ item.label }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item
          has-feedback
          :label="t('addAndEditProject', '相关课程')"
          name="course"
          style="width: 200px"
        >
          <!-- <a-select v-model:value="formModel.course" mode="multiple" style="width: 100%; margin-right: 12px"
            :placeholder="t('common','相关课程')">
            <a-select-option :value="item.dictValue" v-for="item in newSelectStructure.course">{{ item.dictName
              }}</a-select-option>
          </a-select> -->
          <a-select
            v-model:value="formModel.course"
            mode="multiple"
            style="width: 100%; margin-right: 12px"
            :placeholder="t('common', '请选择')"
            show-search
            :filter-option="filterOption"
            :options="newSelectStructure.course"
            :field-names="{ label: 'dictName', value: 'dictValue' }"
          >
          </a-select>
        </a-form-item>
        <a-form-item
          has-feedback
          :label="t('addAndEditProject', '成员总数')"
          name="totalMemberLimit"
          style="width: 200px"
        >
          <div style="display: flex; align-items: center">
            <a-input-number
              style="width: 100%; margin-right: 12px"
              v-model:value="formModel.totalMemberLimit"
              autocomplete="off"
            />
            {{ t('addAndEditProject', '人') }}
          </div>
        </a-form-item>
        <a-form-item
          has-feedback
          :label="t('addAndEditProject', '开发模型')"
          name="devModel"
          style="width: 200px"
        >
          <a-select
            v-model:value="formModel.devModel"
            style="width: 100%; margin-right: 12px"
            :placeholder="t('common', '请选择')"
          >
            <a-select-option
              :value="item.dictValue"
              v-for="item in newSelectStructure.devModel"
              >{{ item.dictName }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item
          has-feedback
          :label="t('addAndEditProject', '小组人数设置')"
          name="groupMemberLimit"
          v-if="formModel.template == 1"
        >
          <div style="display: flex; align-items: center; width: 200px">
            <a-input-number
              style="width: 100%; margin-right: 12px"
              v-model:value="formModel.groupMemberLimit"
              autocomplete="off"
            />
            <div
              style="min-width: 30px; text-align: right; white-space: nowrap"
            >
              {{ t('addAndEditProject', '人') }}
            </div>
          </div>
        </a-form-item>
        <div style="width: 200px"></div>
      </div>
      <div class="subTitle required">{{
        t('addAndEditProject', '岗位人数设置')
      }}</div>
      <a-form-item name="projectJobDTOList">
        <div style="display: flex; flex-direction: column; align-items: center">
          <div
            v-for="(item, index) in formModel.projectJobDTOList"
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
              width: 100%;
            "
          >
            <a-form-item
              has-feedback
              :label="t('addAndEditProject', '岗位')"
              name="gangwei"
            >
              <a-input
                style="width: 200px"
                v-model:value="item.name"
                autocomplete="off"
              />
            </a-form-item>
            <a-form-item
              has-feedback
              :label="t('addAndEditProject', '招募人数')"
              name="requiredNum"
              style="margin: 0 12px"
            >
              <a-input-number
                style="width: 200px"
                v-model:value="item.requiredNum"
                autocomplete="off"
              />
            </a-form-item>
            <a-form-item
              has-feedback
              :label="t('addAndEditProject', '技能描述')"
              name="skill"
            >
              <a-textarea style="width: 200px" v-model:value="item.skill"  :auto-size="{ minRows: 1, maxRows: 3 }" :show-count="false" />
              <!-- <a-input
                style="width: 200px"
                v-model:value="item.skill"
                autocomplete="off"
              /> -->
            </a-form-item>
            <MinusCircleOutlined
              v-if="formModel.projectJobDTOList.length > 1"
              style="padding: 0 20px; font-size: 20px; cursor: pointer"
              @click="handleClick({ name: '弹窗_删除招募信息', index })"
            />
          </div>
          <PlusCircleOutlined
            v-if="!disabled"
            style="padding: 20px 0; font-size: 20px; cursor: pointer"
            @click="handleClick({ name: '弹窗_增加招募信息' })"
          />
        </div>
      </a-form-item>
      <!-- <div class="subTitle" v-if="formModel.template == 1">小组人数设置</div>
      <a-form-item has-feedback :label="t('addAndEditProject','小组最多')" name="groupMemberLimit" v-if="formModel.template == 1">
        <div style="display: flex;align-items: center;">
          <a-input-number style="width: 100%;margin-right: 12px;" v-model:value="formModel.groupMemberLimit" autocomplete="off" />
          <div style="width: 30px;text-align: right;">人</div>
        </div>
      </a-form-item> -->
      <a-form-item
        has-feedback
        :label="t('addAndEditProject', '项目目标')"
        name="target"
      >
        <!-- <a-textarea v-model:value="formModel.target" /> -->

        <minEditor  v-model="formModel.target"></minEditor>
      </a-form-item>
      <a-form-item
        has-feedback
        :label="t('addAndEditProject', '项目描述')"
        name="describe"
      >
        <!-- <a-textarea v-model:value="formModel.describe" /> -->

        <minEditor  v-model="formModel.describe"></minEditor>
      </a-form-item>
      <a-form-item
        has-feedback
        :label="t('addAndEditProject', '报名时间')"
        name="registrationStartTime"
      >
        <minRangePicker
          style="width: 100%"
          picker="datetime"
          v-model:startTime="formModel.registrationStartTime"
          v-model:endTime="formModel.registrationEndTime"
        />
      </a-form-item>
      <a-form-item
        has-feedback
        :label="t('addAndEditProject', '项目周期')"
        name="startTime"
      >
        <minRangePicker
          style="width: 100%"
          picker="datetime"
          v-model:startTime="formModel.startTime"
          v-model:endTime="formModel.endTime"
        />
      </a-form-item>
      <a-form-item
        has-feedback
        :label="t('addAndEditProject', '项目难度')"
        name="difficulty"
      >
        <a-rate v-model:value="formModel.difficulty" />
      </a-form-item>
      <a-form-item
        has-feedback
        :label="t('addAndEditProject', '评分标准')"
        name="scoreStandard"
      >
        <!--        <a-textarea v-model:value="formModel.scoreStandard" />-->
        <minEditor  v-model="formModel.scoreStandard"></minEditor>
      </a-form-item>
      <!-- <a-form-item has-feedback :label="t('addAndEditProject','主指导老师')" name="mainTeacherId">
        <a-select v-model:value="formModel.mainTeacherId" :options="newSelectStructure.coTeacherIds" :placeholder="t('common','请选择')"
          style="width: 100%" :field-names="{ label: 'name', value: 'id' }"></a-select>
      </a-form-item> -->
      <a-form-item
        has-feedback
        :label="t('addAndEditProject', '副指导老师')"
        name="coTeacherIds"
      >
        <a-select
          v-model:value="formModel.coTeacherIds"
          :field-names="{ label: 'name', value: 'id' }"
          :disabled="false"
          :options="newSelectStructure.coTeacherIds"
          :placeholder="t('common', '请选择')"
          mode="multiple"
          style="width: 100%"
          show-search
          :filter-option="coTeacherFilterOption"
        ></a-select>
      </a-form-item>

      <a-form-item
        has-feedback
        :label="t('addAndEditProject', '项目图片')"
        name="coverImg"
      >
        <minUploadImage
          :disabled="false"
          v-model="formModel.coverImg"
          v-model:previewImage="formModel.coverImgUrl"
          :customUploadImage="customUploadImage"
        />
      </a-form-item>

      <a-form-item
        v-if="!disabled"
        style="text-align: center; padding-top: 20px"
      >
        <a-button
          :disabled="false"
          type="primary"
          @click="handleSubmit"
          :loading="loading"
          >{{ t('common', '提交') }}</a-button
        >
        <a-button
          :disabled="false"
          style="margin-left: 20px"
          @click="handleCancel"
          >{{ t('common', '取消') }}</a-button
        >
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup>
import { PlusCircleOutlined, MinusCircleOutlined } from '@ant-design/icons-vue'

import minDatePicker from '@/components/common/minDatePicker.vue'
import minRangePicker from '@/components/common/minRangePicker.vue'
import minUploadImage from '@/components/common/minUploadImage.vue'
import minMultipleUploadImage from '@/components/common/minMultipleUploadImage.vue'
import minEditor from '@/components/common/minEditor.vue'
import {
  ossUpload,
  teacherGradeClassFindAll,
  typeCategory,
  teacherList,
} from '@/request/addAndEditProject'
import { defineProps, ref, defineEmits, watch, shallowRef, onBeforeUnmount } from 'vue'
import { message } from 'ant-design-vue'
import { t } from '@/i18n'

const filterOption = (input, option) => {
  return option.dictName.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

const coTeacherFilterOption = (input, option) => {
  return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

const {
  modelValue,
  customUploadImage,
  rules,
  disabled,
  selectStructure,
  loading,
} = defineProps({
  modelValue: Object,
  selectStructure: {
    type: Object,
    default: {},
  },
  customUploadImage: {
    type: Function,
    default: async (info) => {
      let res = await ossUpload({
        file: info.file,
        dir: 'teacher/avatar',
      })
      if (res) return res.data
    },
  },
  rules: {
    type: Object,
    default: {
      name: [
        { required: true, message: t('common', '请输入'), trigger: 'change' },
      ],
      grade: [
        { required: true, message: t('common', '请输入'), trigger: 'change' },
      ],
      groupMemberLimit: [
        { required: true, message: t('common', '请输入'), trigger: 'change' },
      ],
      category: [
        { required: true, message: t('common', '请选择'), trigger: 'change' },
      ],
      template: [
        { required: true, message: t('common', '请选择'), trigger: 'change' },
      ],
      course: [
        {
          required: true,
          message: t('common', '请选择'),
          trigger: 'change',
          type: 'array',
        },
      ],
      totalMemberLimit: [
        { required: true, message: t('common', '请输入'), trigger: 'change' },
      ],
      devModel: [
        { required: true, message: t('common', '请输入'), trigger: 'change' },
      ],
      target: [
        { required: true, message: t('common', '请输入'), trigger: 'change' },
      ],
      difficulty: [
        { required: true, message: t('common', '请输入'), trigger: 'change' },
      ],
      describe: [
        { required: true, message: t('common', '请输入'), trigger: 'change' },
      ],
      registrationStartTime: [
        { required: true, message: t('common', '请输入'), trigger: 'change' },
      ],
      startTime: [
        { required: true, message: t('common', '请输入'), trigger: 'change' },
      ],
      coverImg: [{ message: t('common', '请选择'), trigger: 'change' }],
      projectJobDTOList: [
        {
          async validator(_rule, value) {
            const isValid = value.every(
              (item) => item.name && item.requiredNum && item.skill
            )
            return isValid
              ? Promise.resolve()
              : Promise.reject(t('addAndEditProject', '请完善岗位信息'))
          },
          trigger: 'change',
        },
      ],
    },
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  loading: {
    type: Boolean,
    default: false,
  },
})
const formRef = ref()
const specialDisabled = ref(false)
const teacherStructure = ref([])
const formModel = ref({...JSON.parse(JSON.stringify(modelValue))})
if (modelValue?.startTime)
  specialDisabled.value = new Date() > new Date(modelValue.startTime)

const newSelectStructure = ref({
  ...selectStructure,
  template: [
    { label: t('common', '经典'), value: 0 },
    { label: t('common', '多组协作'), value: 1 },
  ],
})
const emit = defineEmits(['handleSubmit', 'handleCancel'])

watch(
  () => modelValue,
  (newval) => {
    formRef?.value?.resetFields()
    formModel.value = { ...newval }
  }
)
watch(
  () => selectStructure,
  (newval) => {
    newSelectStructure.value = {
      ...newSelectStructure.value,
      ...newval,
    }
  }
)

watch(
  () => formModel.value.coverImg,
  async (newval) => {
    formRef.value.validateFields('coverImg')
  }
)

const gradeShow = async () => {
  let res = await teacherGradeClassFindAll({
    'search_AND_EQ_grade.year': formModel.value.grade,
  })
  if (!res.data) return
  formModel.value.gradeClass = formModel.value.gradeClass
    ? [...formModel.value.gradeClass]
    : []
  newSelectStructure.value.gradeClass = res.data
}
watch(
  () => formModel.value.grade,
  async (newval) => {
    gradeShow()
  }
)
const firstShow = async () => {
  let res = {
    类型: await typeCategory({ field: 'project_category' }),
    课程: await typeCategory({ field: 'course_category' }),
    开发模型: await typeCategory({ field: 'dev_model' }),
    教师列表: await teacherList(),
  }
  if (res['类型']) newSelectStructure.value.category = res['类型'].data
  if (res['课程']) newSelectStructure.value.course = res['课程'].data
  if (res['开发模型']) newSelectStructure.value.devModel = res['开发模型'].data
  if (res['教师列表'])
    newSelectStructure.value.coTeacherIds = res['教师列表'].data
  if (formModel.value.grade) gradeShow()
}
firstShow()
const disabledDate = (time) => {
  return (
    new Date(`${new Date().getFullYear() - 6}/12/31`).getTime() > time.valueOf()
  )
}

const handleSubmit = async () => {
  let v = await formRef.value.validate().catch((err) => false)
  if (!v) return message.error(t('common', '请检查表单数据'))
  emit('handleSubmit', {
    ...formModel.value,
  })
}
const handleCancel = () => {
  emit('handleCancel')
}

const handleClick = async ({ name, record, index }) => {
  switch (name) {
    case '弹窗_增加招募信息':
      formModel.value.projectJobDTOList.push({})
      break
    case '弹窗_删除招募信息':
      formModel.value.projectJobDTOList.splice(index, 1)
      break
  }
}
</script>

<style lang="scss" scoped>
.ant-input-textarea::after {
  display: none;
}
.subTitle {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 10px;
}
.required {
  position: relative;
  /* padding-left: 30rpx; */
}
.required::before {
  content: '*';
  font-size: 16px;
  color: red;
  position: absolute;
  top: 0;
  bottom: 0;
  left: -10px;
  margin: auto;
  display: flex;
  align-items: center;
}
</style>
